<!--
 * @Date: 2024-06-14 16:50:05
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2024-08-29 16:33:48
 * @Description: 收支预算表格 
 * 注:(yhsMode储备添加列表,里面的一户式和添加表单,用新接口,修改,和其他一户式用旧接口)
-->
<template>
  <rk-grid ref="tableRef"
    :="tableAttrs"
    :columns="tableColumns"
    @editClosed="editClosed">
    <template #toolbar_right
      v-if="!editDisabled">
      <el-button v-for="(item, index) in toolbarEnums"
        :key="index"
        :type="item.type"
        plain
        @click="(e) => toolbarHandle(item, e)">{{ item.name }}</el-button>
      <input ref="fileRef"
        :="inputFileAttrs"
        @change="fileInputChange" />
    </template>
  </rk-grid>
</template>

<script setup lang="jsx">
import SzysBaseData from '@/components/designer/cfg/slots-szys-data.json'
import { formSlotProps } from '@/components/designer/cfg/rk-form-pojo.js'
import { RkInputNumber } from '@/components/rk-input'

import { computed, nextTick, onBeforeMount, reactive, toRaw, unref, watch } from 'vue';
import { ElMessage } from 'element-plus';

import { useEnv } from '@/hooks/useEnvHook'
import { RKUtils, XEUtils } from '/@/utils';
import { useFilesSzysApi } from '@/api';
import FileUtils, { FILE_TYPE_ENUM } from '@/utils/file-utils.js';


/*
  Vue3.3以后支持 默认一些自定义属性
*/
defineOptions({
  name: 'ProjectSzysTable',
  mark: 'ProjectSzysTable',
  title: '收支预算表格（新）',
})

// 属性定义
const props = defineProps({
  // 标题
  title: { type: String, default: '收支预算表格（新）'},
  // 通用属性
  ...formSlotProps
})


// 对应表单的联动字段信息
const formFields = computed(() => {
	const isCts = false
	return {
		// 建设期限字段
		jsqxField: isCts ? 'JS_USED_LIMIT' : 'PRO_BUID_TERM',
		// 运营期限字段
		yyqxField: isCts ? 'YY_USED_LIMIT' : 'PRO_OPER_TERM',
		// 项目期限字段
		xmqxField: isCts ? 'XM_USED_LIMIT' : 'PRO_TERM_1',
    // 申报年度字段
    sbndField: isCts ? 'FISCAL_YEAR' : 'FISCAL_YEAR',
		// 开工日期日期字段
		kgrqField: isCts ? 'XM_USED_DATE' : 'START_DATE',
		// 收支预算-其中专项债券安排资本金
		qzzxAmtField: isCts ? 'XMZGS_AMT' : 'BOND_FUND_AMT',
		// 项目总金额
		xmzgsAmtField: isCts ? 'PRO_TOTAL_AMT' : 'PRO_TOTAL_AMT',
	}
})
// 允许编辑的类型
const allowTypes = ['add', 'edit']
// 禁用编辑 true-禁用 false-启用
const editDisabled = computed(() => {
  return !allowTypes.includes(props.formType)
})
//(储备添加列表,里面的一户式和添加表单,用新接口,修改,和其他一户式用旧接口)
const routeQuery = useRoute().query
const yhsMode = computed(()=>!!(routeQuery.yhsMode && routeQuery.yhsMode === 'ad51'))
// 表格Ref对象
const tableRef = ref(null)
// 表格属性
const tableAttrs = reactive({
  data: [],
  title: '收支预算明细（单位：万元）',
  keyField: 'BAL_ID',
  seqConfig: false,
  keepSource: true,
  editConfig: !editDisabled.value,
  showFooter: false,
  pagerConfig: false,
  rowClassName: ({ row }) => {
    if (row.TRUN_BG_COLOR == 1) return 'row-background'
  },
  toolbarConfig: { refresh: false },
})
// 表格数据集
const tableStore = reactive({
  // 公式数据集
  formulas: null,
  // 动态添加的字段
  dynamicColumns: [],
  // 是否进行了利息测算
  isInterestMeasurement: false,
})
// 表格字段
const tableColumns = reactive([
  {
    field: 'BAL_TYPE_NAME',
    title: '收支类别',
    width: 280,
    align: 'left',
    fixed: 'left',
    sortable: false,
    className: 'col-background',
		slots: { default: ({ row, column }) => {
			return [
				<span v-html={row[column.field]}></span>
			]
		}}
  },
  {
    field: 'BAL_TYPE_CODE',
    title: '类别编码',
    width: 100,
    align: 'left',
    fixed: 'left',
    visible: false,
    className: 'col-background',
  },
  {
    field: 'BAL_FORMULA',
    title: '公式',
    width: 130,
    align: 'center',
    fixed: 'left',
    sortable: false,
    className: 'col-background',
  },
  {
		field: 'TOTAL_AMT',
		title: '合计',
    fixed: 'left',
		sortable: false,
    children: [
      {
				field: 'SRAMT_Y',
				title: '收入',
				width: 120,
				align: 'right',
        className: 'col-background',
				formatter: ['formatThousand'],
			},
			{
				field: 'ZCAMT_Y',
				title: '支出',
				width: 120,
				align: 'right',
        className: 'col-background',
				formatter: ['formatThousand'],
			},
    ]
  }
])

/** 加载表格字段 */
const loadColumns = () => {
  for (let i = tableColumns.length; i > 0; i--) {
    if (tableColumns[i-1].field === 'TOTAL_AMT') {
      break;
    }
    tableColumns.pop()
  }
  const { formData } = props
  const { formatNumber } = RKUtils
  // 建设期限
  const jsqx = formatNumber(formData[formFields.value.jsqxField])
  // 运营期限
  const yyqx = formatNumber(formData[formFields.value.yyqxField])
  // 项目期限
  // const xmqx = formatNumber(formData[formFields.value.xmqxField])
  const xmqx = (jsqx + yyqx)
  // 开工日期
  const startDate = formData[formFields.value.kgrqField]
  // 当前年
  const startYear = startDate ? Number(startDate.substring(0, 4)) : new Date().getFullYear()

  let limitYear = (jsqx + yyqx)
  let exceedLimit = false
  if (!limitYear || (limitYear && limitYear < 0)) {
    limitYear = 4
  }
  if (limitYear >= 30) {
    limitYear = 30
    exceedLimit = true
  }

  tableStore['jsqx'] = jsqx
  tableStore['yyqx'] = yyqx
  tableStore['xmqx'] = xmqx
  tableStore['limitYear'] = limitYear
  tableStore['startYear'] = startYear
  tableStore['dynamicColumns'] = []
  for (let i = 0; i <= limitYear; i++) {
    let year = startYear + i
    if (i === limitYear && exceedLimit) {
      year = `${year}及以后`
    }
    const colItem = {
      field: `TOTAL_Y${i}`,
      title: year,
      sortable: false,
      children: [
        {
          field: `SRAMT_Y${i}`,
          title: '收入',
          width: 120,
          align: 'right',
          formatter: (args) => columnFormatter(args),
          editRender: { autofocus: '.el-input__inner' },
          slots: { edit: (args) => editSlotRender(args) }
        },
        {
          field: `ZCAMT_Y${i}`,
          title: '支出',
          width: 120,
          align: 'right',
          formatter: (args) => columnFormatter(args),
          editRender: { autofocus: '.el-input__inner' },
          slots: { edit: (args) => editSlotRender(args) }
        }
      ]
    }
    tableColumns.push(colItem)
    tableStore.dynamicColumns.push(colItem)
  }
  // 重新计算合计列数据
  calcTotalCol()
}
// 数字输入框配置
const numberConfig = reactive({
  min: 0,
  style: { width: '100%' },
  undeline: false,
  precision: 2,
  placeholder: '请输入'
})
/** 可以编辑的单元格数据 */
const isNotEditCell = (row, column) => {
  // [22-财务费用-专项债券付息] | [42-财务费用-专项债券付息支出]
  let flag = (row.BAL_TYPE_CODE == '22' || row.BAL_TYPE_CODE == '42')
  if (column.field.startsWith('SRAMT_Y')) {
    flag = (row.IS_SR_EDIT != 1 || flag)
  }
  if (column.field.startsWith('ZCAMT_Y')) {
    flag = (row.IS_ZC_EDIT != 1 || flag)
  }
  return flag
}
/**
 * 获取编辑渲染
 *
 * @param param 参数 { row, column }
 */
const editSlotRender = ({ row, column }) => {
  if (isNotEditCell(row, column)) {
    return '--'
  } else {
    // [1-建设资金来源][2-项目建设支出][3-项目运营预期收入]
    if (['1', '2', '3'].includes(row.BAL_TYPE_CODE)) {
      return formatThousand(row[column.field])
    } else {
      return [
        <RkInputNumber
          {...numberConfig}
          v-model={row[column.field]}
        />
      ]
    }
  }
}
/**
 * 字段通用格式化方法
 * 
 * @param param 参数 { cellValue, row, column }
 */
const columnFormatter = ({ cellValue, row, column }) => {
  if (isNotEditCell(row, column)) {
    return '--'
  } else {
    return formatThousand(cellValue)
  }
}

// 表格工具栏枚举
const toolbarEnums = {
  'LXCS': { name: '利息测算', type: 'primary', code: 'LXCS' },
  'MBXZ': { name: '模版下载', type: 'primary', code: 'MBXZ' },
  'MBDR': { name: '模版导入', type: 'primary', code: 'MBDR' },
  'TBSM': { name: '填报说明', type: 'primary', code: 'TBSM' },
}
/**
 * 表格工具栏触发事件
 * 
 * @param item 按钮枚举
 */
const toolbarHandle = async (item, e) => {
  switch(item.code) {
    case toolbarEnums.LXCS.code:
      handleCalcLxcs(e)
      break;
    case toolbarEnums.MBXZ.code:
      ElMessage.info('文件正在下载中，请稍候......')
      try {
        const result = await useFilesSzysApi().downloadSzysTemplate()
        FileUtils.dowloadFile(result, '收支预算模板', FILE_TYPE_ENUM.excel);
      } catch(error) {
        console.error(error)
      }
      break;
    case toolbarEnums.MBDR.code:
      importFile()
      break;
    case toolbarEnums.TBSM.code:
      window.open('/html/szys-tbsm.html', '_blank');
      break;
    default:
      break;
  }
}
/** 计算利息测算 */
const handleCalcLxcs = (e) => {
  if (!tableRef.value) return
  const { fullData: gridData } = tableRef.value.getTableData()
  if (XEUtils.isEmpty(gridData)) return
  const { formData } = props
  // 建设期限，运营期限
  const { jsqx, yyqx } = tableStore
  if ((jsqx + yyqx) <= 0) {
    ElMessage.error('请输入项目建设期限和项目运营期限！')
    return
  }
  
  // 获取每年专项债券发行额 [12]
  let zqfxMap = gridData[2];
  // 获取每年专项债券还本额 [5]
  let zqhbMap = gridData[21];
  let qxStart = -1,
      qxEnd = -1;
  // 计算债券期限
  for (let i = 0; i < jsqx + yyqx + 1; i++) {
    // 最先发债年
    let syKey = 'SRAMT_Y' + i;
    if (zqfxMap[syKey] * 1 > 0 && qxStart * 1 < 0) {
      qxStart = i;
    }
    // 最后还本年
    let zcKey = 'ZCAMT_Y' + i;
    if (zqhbMap[zcKey] * 1 > 0) {
      qxEnd = i;
    }
  }
  // 债券发行期限 = 最后还本年 - 最先发债年
  let zqqx = qxEnd - qxStart;
  if (zqqx < 0) {
    ElMessage.error("请输入地方政府债券发行额和专项债券还本额！");
    return
  }

  zqqx = jsqx + yyqx;
  // 获取[本次申报-债券期限]
  let fZqqx = formData['DEBT_DEADLINE_CODE']
  zqqx = fZqqx ? parseInt(fZqqx) : zqqx
  // 债券利率
  let zqlv = zqqx > 5 ? 0.032 : 0.03;
  // 根据第一年债券发行，计算第二年付息
  let Amt_all = 0;
  for (let i = 0; i <= jsqx; i++) {
    // 计算建设期总金额
    let srKey = 'SRAMT_Y' + (i);
    Amt_all += gridData[2][srKey] * 1;
  }
  for (let i = 0; i <= zqqx; i++) {
    let zcKey = 'ZCAMT_Y' + (i + 1);
    gridData[9][zcKey] = 0;
    gridData[18][zcKey] = 0;
  }

  // 赋值合计金额
  gridData[9]['ZCAMT_Y'] = formatValue(Amt_all * zqlv * jsqx); //（二）财务费用-专项债券付息
  gridData[18]['ZCAMT_Y'] = formatValue(Amt_all * zqlv * yyqx); //（二）财务费用-专项债券付息支出

  if (!tableStore.formulas) { analyzeFormulas(gridData) }
  const { formulas } = tableStore
  calcRowFormula(gridData, formulas['B'], 'ZCAMT_Y')
  calcRowFormula(gridData, formulas['D'], 'ZCAMT_Y')

  if (e) {
    tableStore.isInterestMeasurement = true
    ElMessage.success('利息测算成功！')
  }
}

/** 模版导入相关操作 -- 开始 */
const fileRef = ref(null)
const importFile = () => {
  const { jsqx, yyqx } = tableStore
  if ((jsqx + yyqx) <= 0) {
    ElMessage.warning('请输入项目建设期限和项目运营期限！')
    return
  }
  fileRef.value.click()
}
const importStore = {
  headerJson: '{"BAL_TYPE_NAME":"收支类别", "BAL_FORMULA":"公式", "SRAMT_Y":"收入求和", "ZCAMT_Y":"支出求和", ' +
  '"SRAMT_Y0":"T年收入金额", "ZCAMT_Y0":"T年支出金额", "SRAMT_Y1":"T+1年收入金额", "ZCAMT_Y1":"T+1年支出金额", ' +
  '"SRAMT_Y2":"T+2年收入金额", "ZCAMT_Y2":"T+2年支出金额", "SRAMT_Y3":"T+3年收入金额", "ZCAMT_Y3":"T+3年支出金额", ' +
  '"SRAMT_Y4":"T+4年收入金额", "ZCAMT_Y4":"T+4年支出金额", "SRAMT_Y5":"T+5年收入金额", "ZCAMT_Y5":"T+5年支出金额", ' +
  '"SRAMT_Y6":"T+6年收入金额", "ZCAMT_Y6":"T+6年支出金额", "SRAMT_Y7":"T+7年收入金额", "ZCAMT_Y7":"T+7年支出金额", ' +
  '"SRAMT_Y8":"T+8年收入金额", "ZCAMT_Y8":"T+8年支出金额", "SRAMT_Y9":"T+9年收入金额", "ZCAMT_Y9":"T+9年支出金额", ' +
  '"SRAMT_Y10":"T+10年收入金额", "ZCAMT_Y10":"T+10年支出金额", "SRAMT_Y11":"T+11年收入金额", "ZCAMT_Y11":"T+11年支出金额", ' +
  '"SRAMT_Y12":"T+12年收入金额", "ZCAMT_Y12":"T+12年支出金额", "SRAMT_Y13":"T+13年收入金额", "ZCAMT_Y13":"T+13年支出金额", ' +
  '"SRAMT_Y14":"T+14年收入金额", "ZCAMT_Y14":"T+14年支出金额", "SRAMT_Y15":"T+15年收入金额", "ZCAMT_Y15":"T+15年支出金额", ' +
  '"SRAMT_Y16":"T+16年收入金额", "ZCAMT_Y16":"T+16年支出金额", "SRAMT_Y17":"T+17年收入金额", "ZCAMT_Y17":"T+17年支出金额", ' +
  '"SRAMT_Y18":"T+18年收入金额", "ZCAMT_Y18":"T+18年支出金额", "SRAMT_Y19":"T+19年收入金额", "ZCAMT_Y19":"T+19年支出金额", ' +
  '"SRAMT_Y20":"T+20年收入金额", "ZCAMT_Y20":"T+20年支出金额", "SRAMT_Y21":"T+21年收入金额", "ZCAMT_Y21":"T+21年支出金额", ' +
  '"SRAMT_Y22":"T+22年收入金额", "ZCAMT_Y22":"T+22年支出金额", "SRAMT_Y23":"T+23年收入金额", "ZCAMT_Y23":"T+23年支出金额", ' +
  '"SRAMT_Y24":"T+24年收入金额", "ZCAMT_Y24":"T+24年支出金额", "SRAMT_Y25":"T+25年收入金额", "ZCAMT_Y25":"T+25年支出金额", ' +
  '"SRAMT_Y26":"T+26年收入金额", "ZCAMT_Y26":"T+26年支出金额", "SRAMT_Y27":"T+27年收入金额", "ZCAMT_Y27":"T+27年支出金额", ' +
  '"SRAMT_Y28":"T+28年收入金额", "ZCAMT_Y28":"T+28年支出金额", "SRAMT_Y29":"T+29年收入金额", "ZCAMT_Y29":"T+29年支出金额", ' +
  '"SRAMT_Y30":"T+30年收入金额", "ZCAMT_Y30":"T+30年支出金额"}',
  headerRowNumber: 2,
}
const inputFileAttrs = reactive({
  type: 'file',
  accept: '.xls, .xlsx',
  style: { display: 'none' }
})
const fileInputChange = async (e) => {
  const file = e.target.files[0]
  const { name } = file
  const { accept } = inputFileAttrs
  const suffix = name.substring(name.lastIndexOf('.'), name.length)
  if (accept && !accept.includes(suffix)) {
    ElMessage.error(`文件类型错误，请选择文件${accept}`)
    return
  }
  const formData = new FormData()
  formData.append('excelFile', file);
	formData.append('headerJson', importStore.headerJson);
	formData.append('headerRowNumber', importStore.headerRowNumber);

  const result = await useFilesSzysApi().uploadSzysFile(formData)
  fileRef.value.value = null;
  if (result && result.length > 0) {
    const resData = XEUtils.clone(result, true)
    tableAttrs.data = converImportData(resData)
    setContactFormData()
    ElMessage.success('导入成功！')
  } else {
    ElMessage.error('导入失败，未能匹配到数据！')
  }
}
const converImportData = (importData) => {
  const tableData = tableAttrs.data
  const coverTableData = []
  tableData.forEach(row => {
    let coverRow = XEUtils.clone(row, true)
    let importRow = importData.find(item => item.BAL_FORMULA === row.BAL_FORMULA)
    for (let key in importRow) {
      if (!(key.includes('SRAMT_Y') || key.includes('ZCAMT_Y'))) continue;
      coverRow[key] = RKUtils.formatNumber(importRow[key])
    }
    coverTableData.push(coverRow)
  })
  return coverTableData
}
/** 模版导入相关操作 -- 结束 */

/**
 * 复制表格数据，主要是统一穿透式，一体化，项目筹划收支预算列表数据
 * 
 * @param data 请求的表格数据
 */
const copyTableData = (data) => {
  let newTableData = []
  for (let baseRow of SzysBaseData) {
    let resRow = XEUtils.isEmpty(data) ? {} : data.find(item => {
      if (item.BAL_FORMULA) {
        return item.BAL_FORMULA.trim() === baseRow.BAL_FORMULA.trim()
      } else if (item.BAL_TYPE_CODE) {
        return item.BAL_TYPE_CODE.trim() === baseRow.BAL_TYPE_CODE.trim()
      } else {
        return false
      }
    })
    let tempRow = baseRow
    if (resRow) {
      tempRow = { ...resRow, ...baseRow,  }
      if (!resRow.BAL_ID) {
        tempRow.BAL_ID = RKUtils.getGuid()
        tempRow.SET_YEAR = tableStore.startYear
      }
      for (let key in resRow) {
        let srRegxRes = key.match(new RegExp(`^SRAMT_Y([0-9]{0,})$`))
        let zcRegxRes = key.match(new RegExp(`^ZCAMT_Y([0-9]{0,})$`))
        if (!(srRegxRes || zcRegxRes)) continue;
        tempRow[key] = resRow[key]
      }
    } else {
      if (!tempRow.BAL_ID) {
        tempRow.BAL_ID = RKUtils.getGuid()
        tempRow.SET_YEAR = tableStore.startYear
      }
    }
    newTableData.push(tempRow)
  }
  return newTableData
}
/** 加载表格数据 */
const loadTableData = async () => {
  const { busiInfo, formData } = props
  let proId = ''
  if (XEUtils.isEmpty(busiInfo)) {
    proId = formData.proId || 'designer'
  } else {
    proId = busiInfo.proId || 'designer'
  }
  let request = null
  // TODO 四川环境特殊处理 (yhsMode储备添加列表,里面的一户式和添加表单,用新接口,修改,和其他一户式用旧接口)
  if (useEnv().isSiChuanEnv && (props.buttonCode === 'add' || yhsMode.value)) {
    request = useFilesSzysApi().getSzysDataByProIdFormAd51
  } else {
    request = useFilesSzysApi().getSzysDataByProId
  }
  await request({ proId, proTypeId: '' })
  .then(res => {
    let resData = []
    const { code, data, msg } = res
    if (code === 200) {
      resData = copyTableData(data)
    } else {
      resData = copyTableData([])
      console.error('获取收支预算列表信息出错:', msg)
    }
    // 建设期限
    const jsqx = RKUtils.formatNumber(props.formData[formFields.value.jsqxField])
    // 运营期限
    const yyqx = RKUtils.formatNumber(props.formData[formFields.value.yyqxField])
    if (jsqx || yyqx) {
      handleCalcLxcs()
    }
    tableAttrs.data = resData
  })
  .catch(err => {
    console.error('获取收支预算列表信息出错:', err)
  })
}
/** 处理数据的开始年度 */
const setDataSetYear = () => {
  const { startYear } = tableStore
  tableAttrs.data.forEach(row => {
    row.SET_YEAR = startYear
  })
}
/** 解析表格中的公式数据 */
const analyzeFormulas = (tableData) => {
  let formulas = {};
	tableData.forEach((item) => {
    const { BAL_FORMULA } = item
		if (BAL_FORMULA && BAL_FORMULA.includes('=')) {
			let rowFormula = item.BAL_FORMULA.trim();
			let fl = rowFormula.split('=');
      if (fl && fl.length) {
        let formulaRules = [rowFormula]
        let calcFls = fl[1].split(/(\-|\+|\*|\/)/);
        formulaRules.push(...calcFls)
        formulas[fl[0]] = formulaRules
        let flsCode = fl[1].split(/[-+*/]/);
        flsCode.forEach(code => {
          formulas[code] = formulaRules
        })
      }
		}
	});
  tableStore.formulas = formulas
  return formulas
}

/** 重置利息测算数据 */
const resetLxcs = () => {
  if (!tableRef.value) return
  tableStore.isInterestMeasurement = false
  const { tableData } = tableRef.value.getTableData()
  const rowCode22 = tableData.find(item => item.BAL_TYPE_CODE == '22')
  const rowCode42 = tableData.find(item => item.BAL_TYPE_CODE == '42')
  rowCode22['ZCAMT_Y'] = 0
  rowCode42['ZCAMT_Y'] = 0
}
/**
 * 单元格编辑状态下被关闭时会触发该事件
 * 
 * @param param { row, column }
 */
const editClosed = ({ row, column }) => {
  resetLxcs()
  calcTableRow(row, column)
}
/** 计算行 */
const calcTableRow = (row, column) => {
  const { tableData } = tableRef.value.getTableData()
  if (!tableStore.formulas) { analyzeFormulas(tableData) }
  const { formulas } = tableStore
  // 计算公式数组
  let rowFls = formulas[row.BAL_FORMULA]
  calcRowFormula(tableData, rowFls, column.field)
  calcTotalCol()
}
/**
 * 根据公式计算行数据
 * 
 * @param tableData 表格数据
 * @param rowFls 公式
 * @param field 字段
 */
const calcRowFormula = (tableData, rowFls, field) => {
  let flsTotal = 0
  if (rowFls) {
    // 计算公式符号
    let rowFlsSym = ''
    for (let i = 1; i < rowFls.length; i++) {
      let flCode = rowFls[i]
      if (i % 2 === 0) {
        rowFlsSym += flCode
      } else {
        const flRow = tableData.find(item => item.BAL_FORMULA === flCode)
        const flRowValue = formatValue(flRow[field]) || 0
        switch(rowFlsSym) {
          case '+':
            flsTotal = flsTotal + flRowValue
            break;
          case '-':
            flsTotal = flsTotal - flRowValue
            break;
          case '*':
            flsTotal = flsTotal * flRowValue
            break;
          case '/':
            flsTotal = flsTotal / flRowValue
            break;
          default:
            flsTotal = flsTotal + flRowValue
            break;
        }
      }
    }
    // 设置公式结果行数据
    const flsTotalRow = tableData.find(item => item.BAL_FORMULA.trim() === rowFls[0])
    flsTotalRow[field] = formatValue(flsTotal)
  }
}
/** 计算数据合计列 */
const calcTotalCol = async () => {
  if (!tableRef.value) return
  const { tableData } = tableRef.value.getTableData()
  const { limitYear } = tableStore
  for (let row of tableData) {
    let srTotal = 0
    let zcTotal = 0
    for (let i = 0; i <= limitYear; i++) {
      // 根据公式计算合计列
      if (row.IS_SR_EDIT == 1) {
        srTotal += formatValue(row[`SRAMT_Y${i}`]) || 0
      }
      if (row.IS_ZC_EDIT == 1) {
        zcTotal += formatValue(row[`ZCAMT_Y${i}`]) || 0
      }
    }
    row['SRAMT_Y'] = formatValue(srTotal)
    row['ZCAMT_Y'] = formatValue(zcTotal)
  }
  
  setContactFormData(false)
}
/** 设置关联的表单字段数据 */
const setContactFormData = (force=false) => {
  nextTick(() => {
    if (!tableRef.value) return
    if (!force && editDisabled.value) return
    const { tableData } = tableRef.value.getTableData()
    if (XEUtils.isEmpty(tableData)) return
    // 获取转换后的表格数据
    const { typeCodeData } = converTableData(tableData)
    const { formData, setFormValue } = props
    // 申报年度
    let fiscalYear = formData.FISCAL_YEAR
    // 设置[本次申报-本次申报金额]
    setFormValue('APPLY_AMT', typeCodeData['12'].srData[fiscalYear] || 0)
    // 设置[本次申报-申请总金额]
    setFormValue('TOTAL_APP_AMT', typeCodeData['12']['sramtY'])
    // 设置[收支预算-其中专项债券安排资本金]
    setFormValue(formFields.value.qzzxAmtField, typeCodeData['13']['sramtY'])
    // 设置[基本信息-项目总金额]
    setFormValue(formFields.value.xmzgsAmtField, typeCodeData['1']['sramtY'])
  })
}

/**
 * 校验收支预算数据
 * 
 * @param szysArr 收支预算数据
 * @param formData 表单数据
 */
const szysCheck = (szysArr, formData) => {
  const SZYS_TAB_NAME = '收支预算'
  const formFieldsValue = unref(formFields)
  let DEBT_ISUSE_YXZWSBXQ = '0';// 是否使用YX债务项目申报新增项目需求
    let result = {allowPass: true, msg: ""};
    if (szysArr.length == 0) {
        result = {allowPass: false, msg: SZYS_TAB_NAME + "：收支预算不能为空"};
        return result;
    }
    let jsqx = formData[formFieldsValue.jsqxField]; //建设期限
    if (jsqx == 0) {
        result = {allowPass: false, msg: SZYS_TAB_NAME + "：建设期限不能为空"};
        return result;
    }
    let yyqx = formData[formFieldsValue.yyqxField]; //运营期限

    // let xmqx = formData[formFieldsValue.xmqxField]; //项目期限
    let xmqx = (Number(jsqx || 0) + Number(yyqx || 0))
    if (xmqx>30){
        xmqx=30;
    }
    let zqze = 0; // 债券总额
    let zqhbze = 0;// 债券还本总额
    let jscb = 0; //建设成本
    let xmyyqsr = 0;// 项目运营期收入
    let xmzsjysr = 0;//项目自身经营收入
    let xmyycb = 0;//项目运营成本
    let schrz = 0;//项目单位市场化融资
    let schrzhb = 0;//市场化融资还本
    let zxzqfx = 0;//财务费用-专项债券付息
    let schrzfx = 0;//财务费用-市场化融资付息
    let zxzqfxzc = 0;//财务费用-专项债券付息支出
    let schrzfxzc = 0;//财务费用-市场化融资付息支出
    let temp1 = 0;
    let temp2 = 0;

    let reg = /^[+-]?([0-9]+[.][0-9]*|[.][0-9]+)$/;
    let bool = false;
    let isCheckJszjly = true; //校验建设资金来源
    let SRAMT = ''
    // TODO 与一体化差异处 [前期准备，本次申报]
    let qqzbFlag = true, bcsbFlag = true
    if (qqzbFlag && bcsbFlag) {
      bool = true;
      // 申报年度
      let sbnd = Number(formData[formFieldsValue.sbndField])
      // 开工日期
      let kgrq = Number(formData[formFieldsValue.kgrqField].substring(0, 4))
      //
      let num = 0
      if (kgrq != sbnd) {
        num = sbnd - kgrq
      }
      SRAMT = "SRAMT_Y" + num;
    }
    // 中小银行不校验
    if (formData['PRO_TYPE_CODE'] == '30') {
      bool = false
      isCheckJszjly = false
    }

    for (let i in szysArr) {
        if (szysArr[i].BAL_TYPE_CODE == "12") {
            zqze = szysArr[i].SRAMT_Y;
            for (let v=xmqx ;v>jsqx;v--) {
                temp1 = szysArr[i]['SRAMT_Y' + v];
                if (temp1 != 0) {
                    result = {allowPass: false, msg: SZYS_TAB_NAME + "：地方政府专项发债年限不能超过建设期限"};
                    return result;
                }
            }
        }
        if (szysArr[i].BAL_TYPE_CODE == "5") {
            // zqhbze = szysArr[i].SRAMT_Y;
            zqhbze = szysArr[i].ZCAMT_Y;
            temp1 = szysArr[i]['ZCAMT_Y' + 0];
            if (temp1 == zqhbze) {
                result = {allowPass: false, msg: SZYS_TAB_NAME + "：请输入地方政府债券发行额和专项债券还本额！"};
                return result;
            }
        }
        if (szysArr[i].BAL_TYPE_CODE == "21") {
            jscb = szysArr[i].ZCAMT_Y;
        }
        if (szysArr[i].BAL_TYPE_CODE == "3") {
            xmyyqsr = szysArr[i].SRAMT_Y;
        }
        if (szysArr[i].BAL_TYPE_CODE == "32") {
            xmzsjysr = szysArr[i].SRAMT_Y;
        }
        if (szysArr[i].BAL_TYPE_CODE == "41") {
            for (let v=xmqx ;v>jsqx;v--){
                xmyycb += szysArr[i]['ZCAMT_Y'+v];
            }
        }
        if (szysArr[i].BAL_TYPE_CODE == "14") {
            schrz = szysArr[i].SRAMT_Y;
        }
        if (szysArr[i].BAL_TYPE_CODE == "6") {
            schrzhb = szysArr[i].ZCAMT_Y;
        }
        if (szysArr[i].BAL_TYPE_CODE == "13") {
            for (let v = 0; v <= jsqx; v++) {
                temp1 = szysArr[i]['SRAMT_Y' + v];
                temp2 = szysArr[i - 1]['SRAMT_Y' + v];
                if (temp2 < temp1) {
                // if ((temp2 + temp1) < 0) {
                  result = {allowPass: false, msg: SZYS_TAB_NAME + "：每年的其中：用于资本金应小于等于地方政府专项债券"};
                  return result;
                }
            }
        }
        if (szysArr[i].BAL_TYPE_CODE == "22") {
            zxzqfx = szysArr[i].ZCAMT_Y;
        }
        if (szysArr[i].BAL_TYPE_CODE == "23") {
            schrzfx = szysArr[i].ZCAMT_Y;
        }
        if (szysArr[i].BAL_TYPE_CODE == "42") {
            zxzqfxzc = szysArr[i].ZCAMT_Y;
        }
        if (szysArr[i].BAL_TYPE_CODE == "43") {
            schrzfxzc = szysArr[i].ZCAMT_Y;
        }

        // TODO 与一体化差异处
        // 添加校验：修改收支预算表建设资金来源相关项数据填报格式，只允许录入不小于0的万元整数,
        if(isCheckJszjly && szysArr[i].BAL_TYPE_CODE == "1" && reg.test(szysArr[i].SRAMT_Y)){
            result = {allowPass: false, msg: "项目总金额不能为非万元整数！"};
            return result;
        }
        if(bool && szysArr[i].BAL_TYPE_CODE == "12" && reg.test(szysArr[i][SRAMT]) ){
            result = {allowPass: false, msg: "本次申报金额不能为非万元整数！"};
            return result;
        }
    }
    if (zqze == 0) {
        result = {allowPass: false, msg: SZYS_TAB_NAME + "：建设期限内地方政府专项债券总额不能为0"};
        return result;
    }
    if (zqze != zqhbze) {
        result = {allowPass: false, msg: SZYS_TAB_NAME + "：专项债券还本总额应等于地方政府专项债券总额"};
        return result;
    }
    if("1" != DEBT_ISUSE_YXZWSBXQ){
        if (jscb == 0) {
            result = {allowPass: false, msg: SZYS_TAB_NAME + "：项目建设成本不能为0"};
            return result;
        }
        if (xmyycb == 0) {
            result = {allowPass: false, msg: SZYS_TAB_NAME + "：运营期间项目运营成本不能为0"};
            return result;
        }
        if (xmzsjysr == 0) {
            result = {allowPass: false, msg: SZYS_TAB_NAME + "：项目自身经营收入不能为0"};
            return result;
        }
        if (xmyyqsr == 0) {
            result = {allowPass: false, msg: SZYS_TAB_NAME + "：项目运营期收入不能为0"};
            return result;
        }
    }
    if (schrz != schrzhb) {
        result = {allowPass: false, msg: SZYS_TAB_NAME + "：市场化融资还本额应等于市场化融资总金额"};
        return result;
    }
    if(schrzhb > 0 && schrzfx + schrzfxzc <= 0){
        result = {allowPass: false, msg: SZYS_TAB_NAME + "：市场化融资还本不为空时,财务费用-市场化融资付息必须大于0！"};
        return result;
    }
    if (zqze != 0 && zxzqfx == 0) {
        result = {allowPass: false, msg: SZYS_TAB_NAME + "：收支预算信息存在变更操作,请重新进行利息测算！"};
        return result;
    }
    if (yyqx != 0) {
        if (zqze != 0 && zxzqfxzc == 0) {
            result = {allowPass: false, msg: SZYS_TAB_NAME + "：收支预算信息存在变更操作,请重新进行利息测算！"};
            return result;
        }
    }
    /*if(){
        result = {allowPass: false, msg: SZYS_TAB_NAME + "：市场化融资还本额应等于市场化融资总金额"};
        return result;
    }
    if(){
        result = {allowPass: false, msg: SZYS_TAB_NAME + "：市场化融资还本不为0时，市场化融资付息不能为0"};
        return result;
    }*/
    return result;
}

/**
 * 对外暴露的获取插槽数据的方法
 */
const getCompData = () => {
  if (!tableRef.value) return
  const { tableData } = tableRef.value.getTableData()
  const { limitYear } = tableStore
  const resTableData = XEUtils.clone(tableData, true)
  resTableData.forEach(row => {
    for (let key in row) {
      if (!(key.startsWith('SRAMT_Y') || key.startsWith('ZCAMT_Y'))) continue;
      let index = Number(key.replace('SRAMT_Y', '').replace('ZCAMT_Y', '')) || 0;
      if (index > limitYear) { row[key] = 0 }
    }
  })
  return {
    bgtbalance_data: resTableData
  }
}
/**
 * 对外暴露的校验插槽数据的方法
 */
const validateData = () => {
  // 编辑禁用
  if (editDisabled.value) {
    return {
			valid: true, message: '校验通过',
		};
  } else {
    const { fullData: gridData } = tableRef.value.getTableData()
    let result = szysCheck(gridData, props.formData)
    if (result.allowPass) {
      if (!tableStore.isInterestMeasurement) {
        result.allowPass = false
        result.msg = '收支预算页签未进行利息测算，请利息测算之后进行保存!'
      }
    }
    return {
      valid: result.allowPass,
			message: result.msg,
    }
  }
}
/**
 * 加载插槽组件数据，提供给别的插槽或上级组件使用
 */
const loadSlotData = (tableData) => {
  nextTick(() => {
    const { formData, setFormValue } = props
     // 获取转换后的表格数据
    const { typeCodeData } = converTableData(tableData)
    props.slotsData[props.mark] = {
      szysData: XEUtils.clone(tableData, true),
      typeCodeData
    }
    props.slotDataHouse[props.mark] = typeCodeData
    
    // 申报年度
    let fiscalYear = formData.FISCAL_YEAR
    // 设置[本次申报-本次申报金额]
    setFormValue('APPLY_AMT', typeCodeData['12']?.srData[fiscalYear] || 0)
  })
}

/**
 * 处理数据小数点保留位数
 * 
 * @param value 数据
 * @param digits 保留小数点位数
 */
const formatValue = (value, digits = 2) => {
  value = value || 0
  return XEUtils.round(XEUtils.toNumber(value), digits)
}
/**
 * 千分位格式数据
 * 
 * @param value 内容
 * @param digits 小数点位数
 */
const formatThousand = (value, digits = 2) => {
  value = value || 0
  return XEUtils.commafy(XEUtils.round(XEUtils.toNumber(value), digits), { digits })
}
/** 转换表格数据 */
const converTableData = (tableData) => {
  const typeCodeData = {}
  const { limitYear } = tableStore
  tableData.forEach(item => {
    let srData = {}
    let zcData = {}
    let setYear = Number(item.SET_YEAR)
    let balTypeCode = item.BAL_TYPE_CODE
    let balTypeName = item.BAL_TYPE_NAME
    for (let key in item) {
      let srRegxRes = key.match(new RegExp(`^SRAMT_Y([0-9]{1,})$`))
      let zcRegxRes = key.match(new RegExp(`^ZCAMT_Y([0-9]{1,})$`))
      if (!(srRegxRes || zcRegxRes)) continue;
      let value = item[key]
      if (srRegxRes) {
        let srIndex = Number(srRegxRes[1])
        if (srIndex > limitYear) continue;
        srData[setYear + srIndex] = value
      }
      if (zcRegxRes) {
        let zcIndex = Number(zcRegxRes[1])
        if (zcIndex > limitYear) continue;
        zcData[setYear + zcIndex] = value
      }
    }
    typeCodeData[item.BAL_TYPE_CODE] = {
      data: srData,
      srData, zcData,
      sramtY: item.SRAMT_Y,
      zcamtY: item.ZCAMT_Y,
      balTypeCode,
      balTypeName
    }
  })
  return {
    typeCodeData
  }
}

/*
  监听
  [收支预算-建设期限]
  [收支预算-运营期限]
*/
watch(
  [
    () => props.formData[formFields.value.jsqxField],
    () => props.formData[formFields.value.yyqxField],
  ],
  () => {
    loadColumns()
  },
  { deep: false, immediate: true }
)
// 监听 [前期准备-开工日期]
watch(
  () => props.formData[formFields.value.kgrqField],
  (newData) => {
    loadColumns()
    setDataSetYear()
  },
  { deep: false, immediate: true }
)

// 监听 [本次申报-申请年度]
watch(
  () => props.formData.FISCAL_YEAR,
  (newData, oldData) => {
    if (!newData) return
    setContactFormData(true)
  },
  { deep: false, immediate: false }
)

watch(
  () => tableAttrs.data,
  (newData) => {
    loadSlotData(newData)
  },
  { deep: true, immediate: false }
)

onBeforeMount(async () => {
  // 加载表格数据
  await loadTableData()
})


defineExpose({
  getCompData,
  validateData
})

</script>

<style lang="scss" scoped>
:deep(.col-background) {
	background-color: #e6e6e6;
}
:deep(.row-background) {
	background-color: #e6e6e6;
}
</style>